import { component$, Slot, useStyles$ } from '@builder.io/qwik';
import { routeAction$, routeLoader$, useNavigate } from '@builder.io/qwik-city';
import type { RequestHandler } from '@builder.io/qwik-city';

import Footer from '../components/starter/footer/footer';

import styles from './styles.css?inline';
import { checkAuth, logout } from '~/server/authn';
import { QPageHeader } from '~/integrations/react/page-header';

export const onGet: RequestHandler = async ({ cacheControl }) => {
  // Control caching for this request for best performance and to reduce hosting costs:
  // https://qwik.builder.io/docs/caching/
  cacheControl({
    // Always serve a cached response by default, up to a week stale
    staleWhileRevalidate: 60 * 60 * 24 * 7,
    // Max once every 5 seconds, revalidate on the server to get a fresh version of this page
    maxAge: 5,
  });
};

export const useServerTimeLoader = routeLoader$(() => {
  return {
    date: new Date().toISOString(),
  };
});

export const useLoader = routeLoader$(async (requestEvent) => {
  const auth = await checkAuth(requestEvent);
  return auth;
});

export const useLogoutAction = routeAction$(async (props, requestEvent) => {
  await logout(requestEvent.cookie);
  throw requestEvent.redirect(307, '/');
});

export default component$(() => {
  useStyles$(styles);

  const navigate = useNavigate();
  const authSignal = useLoader();
  const logout = useLogoutAction();

  return (
    <>
      <QPageHeader
        client:visible
        authenticated={authSignal.value.ok}
        onLogout$={() => logout.submit()}
        onNavigate$={(url) => navigate(url)}
      />
      <main class="container mx-auto page-content">
        <Slot />
      </main>
      <Footer />
    </>
  );
});
